使用springrest控制器的java
我试图在数据库中发布某些内容时,在使用@RestController时遇到了一些问题。我的目标是尝试获得如下结果:
{
"postID": "5",
"content": "testcontent",
"time": "13.00",
"gender": "Man"
}
在“localhost:port/posts”中发布类似内容时(使用邮递员):
{
"content": "testcontent",
"time": "13.00",
"gender": "Man"
}
帖子。java
package bananabackend;
public class Post {
private final long id;
private String content;
private String time;
private String gender;
// Constructor
public Post(long id, String content, String time, String gender) {
this.id = id;
this.content = content;
this.time = time;
this.gender = gender;
}
// Getters
public String getContent() {
return content;
}
public long getId() {
return id;
}
public String getTime() {
return time;
}
public String getGender() {
return gender;
}
后置控制器。java
package bananabackend;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import bananabackend.Post;
@RestController
public class PostController {
private final AtomicLong counter = new AtomicLong();
@RequestMapping(value="/posts", method = RequestMethod.POST)
public Post postInsert(@RequestParam String content, @RequestParam String time, @RequestParam String gender) {
return new Post(counter.incrementAndGet(), content, time, gender);
}
}
PostRepository。java
package bananabackend;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "posts", path = "posts")
public interface PostRepository extends MongoRepository<Post, String> {
List<Post> findPostByContent(@Param("content") String content);
}
我得到这个错误:
{
"timestamp": 1460717792270,
"status": 400,
"error": "Bad Request",
"exception":
"org.springframework.web.bind.MissingServletRequestParameterException",
"message": "Required String parameter 'content' is not present",
"path": "/posts"
}
我想为每一篇文章设置一个ID,但它似乎不起作用。我试图构建与本指南类似的代码:
# 1 楼答案
您正在尝试获取在请求正文中发送的请求参数。请求参数是您在URL中发送的参数
不要使用
@RequestParam ...
使用@RequestBody Post post
例如:此外,在
Post
类中还需要一个默认构造函数